package modules.intercommunication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import objects.Account;

import modules.configuration.GameConf;
import modules.gameCommunication.GameServerThread;

import common.Constants;
import common.GameServer;
import common.PacketFormatter;

public class InterServerThread implements Runnable {

    private Socket _s;
    private Thread _t;
    private BufferedReader _in;
    private PrintWriter _out;
    private boolean _running = false;

    public InterServerThread(Socket s) {
        _s = s;
        try {
            _in = new BufferedReader(new InputStreamReader(_s.getInputStream()));
            _out = new PrintWriter(_s.getOutputStream());
        } catch (Exception e) {
            return;
        };

        GameServer.setInterServerThread(this);

        _t = new Thread(this);
        _t.start();
    }

    @Override
    public void run() {
        _running = true;
        try {
            String packet = "";
            char charCur[] = new char[1];
            sendPacket(PacketFormatter.getISPasswordPacket(GameConf._interPass));
            while (_in.read(charCur, 0, 1) != -1 && _running) {
                if (charCur[0] != '\u0000' && charCur[0] != '\n' && charCur[0] != '\r') {
                    packet += charCur[0];
                } else if (packet != "") {
                    if (GameConf._debug) {
                        GameServer.writeLine("IS: Recv << " + packet);
                    }
                    parsePacket(packet);
                    packet = "";
                }
            }
        } catch (IOException e) {
        } finally {
            _out.close();
            try {
                _in.close();
            } catch (Exception e) {
            }
            try {
                _s.close();
            } catch (Exception e) {
            }


        }
    }

    private void parsePacket(String packet) {
        byte opcode = Byte.parseByte(packet.substring(0, 2));
        packet = packet.substring(2);

        switch (opcode) {
            //Password accepted
            case 0x00://FIXME Population on configuration ?
                sendPacket(PacketFormatter.getISServerInfoPacket(GameConf._gameServerId, GameServer.getState(), Constants.SERVER_POP_LOW, GameConf._gameAddress, GameConf._useIP, GameConf._gamePort));
                break;
            //Server Information Accepted
            case 0x01:
                GameServer.writeLine("GameServer sucessfully registred to the Realm Server");
                break;
            //Recv a new Account To Register
            case 0x02:
                String[] datas = packet.split(";");
                if (datas.length != 6) {
                    return;
                }
                try {
                    long guid = Long.parseLong(datas[0]);
                    String pseudo = datas[1];
                    byte gmLevel = Byte.parseByte(datas[2]);
                    String answer = datas[3];
                    long subscribeEnd = Long.parseLong(datas[4]);
                    GameServerThread.addWaitingAccount(new Account(guid, pseudo, gmLevel, answer, subscribeEnd));
                } catch (Exception e) {
                }
                break;
        }
    }

    public void sendPacket(String packet) {
        if (!_s.isConnected() || _s.isClosed()) {
            return;
        }

        try {
            _out.write(packet + (char) 0x00);
            _out.flush();
            if (GameConf._debug) {
                GameServer.writeLine("IS: Send >> " + packet);
            }
        } catch (Exception e) {
            GameServer.writeLine("IS Error: " + e.getMessage());
            _out.close();
            _running = false;
            try {
                _s.close();
            } catch (IOException e1) {
            }
        };
    }

    public void stop() {
        _running = false;
    }
}
